package com.open.api.util;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.open.api.model.ResultModel;

import java.util.HashMap;
import java.util.Map;

/**
 * 加签
 */
public class SignUtil {

    //public static ResultModel getSign(String app_id,String method,String  version,String api_request_id,String private_key, String char_set, String sign_type,String contents){
    public static String getSign(String app_id,String method,String  version,String api_request_id,String private_key, String char_set, String sign_type,String contents){
        ResultModel resultModel=new ResultModel();

        //创建参数
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("app_id",app_id);
        paramMap.put("method",method);
        paramMap.put("version",version);
        paramMap.put("charset",char_set);
        paramMap.put("api_request_id",api_request_id);
        paramMap.put("content",contents);

        //拼接待加签的字符串
        String content = AlipaySignature.getSignContent(paramMap);

        //私钥-对数据加签
        String sign = null;
        try {
            sign = AlipaySignature.rsaSign(content, private_key, char_set,sign_type);
        } catch (AlipayApiException e) {
            System.out.println("私钥-对数据加签异常："+e.getMessage());
            resultModel.setSuccess(false);
            resultModel.setErrorCode("4");
            resultModel.setErrorMsg(e.getErrMsg());
           // return  resultModel;
            return  e.getMessage();
        }

        //添加签名到参数
        paramMap.put("sign", sign);


        System.out.println("签名类型 : " + sign_type + " 编码规则: " + char_set);
        System.out.println("拼接待加签的字符串 : " + content);
        System.out.println("当前签名 : " + sign);

        Map<String,Object> retMap=new HashMap<>();
        retMap.put("签名类型",sign_type);
        retMap.put("编码规则",char_set);
        retMap.put("当前签名",sign);

        resultModel.setSuccess(true);
        resultModel.setData(retMap);
        //return resultModel;
        return sign;
    }
}
